package org.mtmi.ui.links;

/**
 * Collection of known connection ID.
 *
 */
public class CID 
{
	/** connection ID field separator */
	public static final String SEP=":"; //$NON-NLS-1$
	
	/** identify a value generator connection (a source of {@link #VALUE_CONSUMER}) */
	public static final String VALUE_GENERATOR="valueGenerator@LID"; //$NON-NLS-1$
	
	/** identify a value consumer connection (a target of {@link #VALUE_GENERATOR}) */
	public static final String VALUE_CONSUMER="valueConsumer@LID"; //$NON-NLS-1$
	
	/** @return the type of the connection id, this is the first field */
	public static String GetType( String cid )
	{
		int index = cid.indexOf( SEP );
		if( index>=0 ) {
			return cid.substring( 0, index );
		} else {
			return cid;
		}
	}
	
	/** @return the fields composing connection id, the first field is connection type */
	public static String[] GetFields( String cid )
	{
		String fields[] = cid.split( SEP );
		return fields;
	}
	
	/**
	 * @return the field at index composing connection id, the first field (index=0) is connection type.
	 * Returns null if field at given index does not exists.
	 * <p>
	 * Note: that is best practice to use {@link #GetFields(String)} instead of several 
	 * {@link #GetField(String, int)} on same connection id.
	 */
	public static String GetField( String cid, int index )
	{
		String fields[] = cid.split( SEP );
		if( index >=0 && index < fields.length ) { 
			return fields[ index ];
		} else {
			return null;
		}
	}
	
	/**@return the connection id from fields, first must be the connection type */
	public static String Get( String fields[] ) {
		StringBuilder sb = new StringBuilder();
		for( int i=0; i<fields.length; i++ ) {
			if( i>0 ) sb.append( SEP );
			sb.append( fields[i] );
		}
		return sb.toString();
	}
	
	/**@return the connection id from type, and field */
	public static String Get( String type, String field ) {
		return type+SEP+field;
	}
	
	/** Validate a connection between two ID.<p>
	 * For example isValidConnection( VALUE_GENERATOR, VALUE_CONSUMER ) returns true.
	 * @param source_cid the source connection id
	 * @param target_cid the starget connection id
	 * @return true if a connection can be established between source and target.
	 */
//TODO: need to make an interface for this method if control need to override ... wait and see	
	public static boolean IsValidConnection( String source_cid, String target_cid )
	{
		String ts = GetType( source_cid );
		String tt = GetType( target_cid );
		
		if( VALUE_GENERATOR.equals( ts ) ) {
			return VALUE_CONSUMER.equals( tt );
		}
		
		return false;
	}
}
